<template>
  <div class="search">
    <!-- 顶部导航 -->
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    ></van-nav-bar>
    <!-- 搜索区域 -->
    <div class="sear">
      <van-icon class="myicon" name="search" />
      <input
        class="ipt"
        type="text"
        v-model="key"
        @input="inputFn"
        placeholder="请输入搜索关键字"
      />
      <button @click="toResult" class="btn">搜索</button>
    </div>
    <!-- 历史记录-->
    <van-cell-group v-if="!key">
      <van-cell class="mytitle" title="历史记录">
        <template #default>
          <van-icon @click="clear" name="cross" />
        </template>
      </van-cell>
      <van-cell
        v-for="(item, index) in historyList"
        :key="index"
        :title="item"
      />
    </van-cell-group>
    <!-- 联想区域 -->
    <van-cell-group v-else>
      <van-cell class="mytitle" title="联想区域" />
      <van-cell icon="search" v-for="(item, index) in thinkList" :key="index">
        <template #title>
          <span @click="toThinkResult(item)" v-html="item"></span>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getThinkApi } from "@/api";
export default {
  data() {
    return {
      // 搜索框中的关键字
      key: "",
      thinkList: [],
      timer: null,
      historyList: JSON.parse(window.localStorage.getItem("history")) || [],
    };
  },
  methods: {
    clear() {
      this.$dialog
        .confirm({
          title: "警告",
          message: "是否删除历史记录",
        })
        .then(() => {
          // 清除 historyList
          this.historyList = [];
          // 清除 localstorage
          window.localStorage.removeItem("history");
        })
        .catch(() => {
          // on cancel
        });
    },
    // 将搜索记录保存到本地
    saveToLocal(item) {
      // 将关键字保存到 historyList 中
      this.historyList.unshift(item);
      //去重
      this.historyList = [...new Set(this.historyList)];
      // 限长
      if (this.historyList.length > 5) {
        this.historyList.splice(5);
      }
      // 再将 historyList 保存到 Localstorage 中
      window.localStorage.setItem("history", JSON.stringify(this.historyList));
    },
    // 跳转到搜索结果页面(点击联想选项)
    toThinkResult(item) {
      // 将 item 中的 span 替换回来
      //   console.log(item);
      item = item.replace(
        `<span style="color:red">${this.key}</span>`,
        this.key
      );
      this.$router.push(`/search/result?key=${item}`);
      // 保存
      this.saveToLocal(item);
    },
    // 跳转到搜索结果页面
    toResult() {
      this.$router.push(`/search/result?key=${this.key}`);
      // 保存
      this.saveToLocal(this.key);
    },
    inputFn() {
      // 判断 key 中是否有值
      if (!this.key) {
        clearTimeout(this.timer);
        return;
      }
      clearTimeout(this.timer);
      this.timer = setTimeout(async () => {
        const res = await getThinkApi({
          q: this.key,
        });
        // 创建一个不区分大小写的正则
        const reg = new RegExp(this.key, "ig");
        // 让联想内容中的关键字高亮 key => <span style="color:red">key</span>
        this.thinkList = res.data.data.options.map((item) => {
          return item.replace(
            reg,
            `<span style="color:red">${this.key}</span>`
          );
        });
        //   this.thinkList = res.data.data.options;
      }, 500);
    },
  },
};
</script>

<style lang="less">
.search {
  font-size: 14px;
  .sear {
    display: flex;
    margin: 10px;
    position: relative;
    .myicon {
      position: absolute;
      top: 10px;
      left: 10px;
    }
    .ipt {
      height: 34px;
      line-height: 34px;
      background-color: #f7f8fa;
      border-radius: 20px;
      border: none;
      flex: 1;
      padding-left: 30px;
    }
    .btn {
      border: none;
      line-height: 34px;
      background: #fff;
    }
  }
  .mytitle {
    font-weight: 700;
  }
}
</style>